package com.doupi.partner.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.net.URL;

/**
 * http request的请求utils
 */
public class HttpRequestUtils {
	private static final Logger LOGGER = LoggerFactory.getLogger(HttpRequestUtils.class);

	private static String WEB_ROOT = null;

	/**
	 * web domain 全站
	 */
	public static String getWebRoot(ServletRequest servletRequest) {
		if (null == WEB_ROOT) {
			if (servletRequest instanceof HttpServletRequest) {
				try {
					HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
					URL url = new URL(httpRequest.getScheme(), httpRequest.getServerName(), httpRequest.getServerPort(), httpRequest.getContextPath());
					WEB_ROOT = url.toString();
				} catch (Exception e) {
					LOGGER.error("获取网站的webroot失败", e);
				}
			}
		}
		return WEB_ROOT;
	}

	/**
	 * 校验请求是否ajax请求
	 */
	public static boolean isAjax(HttpServletRequest httpRequest) {
		return "XMLHttpRequest".equalsIgnoreCase(httpRequest.getHeader("X-Requested-With"));
	}

	/**
	 * 获取系统的refer地址， 没有返回base path
	 */
	public static String getReferUrl(HttpServletRequest httpRequest) {
		String referer = httpRequest.getHeader("referer");
		if (StringUtils.isBlank(referer)) {
			referer = getWebRoot(httpRequest);
		}
		return referer;
	}

	/**
	 * 获取客户端IP
	 */
	public static String getClientIp(ServletRequest servletRequest) {
		if (servletRequest instanceof HttpServletRequest) {
			HttpServletRequest request = (HttpServletRequest) servletRequest;
			String ip = request.getHeader("X-Forwarded-For");
			if (StringUtils.isNotBlank(ip)) {
				return ip;
			}
			ip = request.getHeader("X-Real-IP");
			if (StringUtils.isNotBlank(ip)) {
				return ip;
			}
			ip = request.getHeader("Proxy-Client-IP");
			if (StringUtils.isNotBlank(ip)) {
				return ip;
			}
			ip = request.getHeader("WL-Proxy-Client-IP");
			if (StringUtils.isNotBlank(ip)) {
				return ip;
			}
		}
		return StringUtils.EMPTY;
	}
}
